﻿#define _CRT_SECURE_NO_WARNINGS 1
#include"list.h"

LTNode* LTbuynode(int x)
{
	LTNode* tmp=(LTNode*)malloc(sizeof(LTNode));
	tmp->val = x;
	return tmp;
}
LTNode* LTInit()//生成哨兵位/
{
	LTNode* tmp = (LTNode*)malloc(sizeof(LTNode));
	tmp->prev = tmp->next = tmp;
	tmp->val = 0;
	return tmp;
}
//头节点无需改变因此传值操作    当头节点发生改变又不想创建变量接受，就可以传址操作
void LTDestroy(LTNode** pphead)
{
	LTNode* pcur = (*pphead)->next;
	while (pcur != *pphead)
	{
		LTNode* tmp = pcur;
		pcur = pcur->next;
		free(tmp);
	}

	free(*pphead);
	*pphead = NULL;
	//完全销毁要手动释放phead
}
void LTPrint(LTNode* phead)
{
	assert(phead);
	LTNode* pcur = phead->next;
	while (pcur != phead)
	{
		printf("%d->", pcur->val);
		pcur = pcur->next;
	}
	printf("\n");
	
}
void LTPushBack(LTNode* phead, LTDataType x)
{
	LTNode* newnode = LTbuynode(x);
	//先改newnode不会影响首尾
	newnode->next = phead;
	newnode->prev = phead->prev;
	phead->prev->next = newnode;
	phead->prev = newnode;
}
void LTPopBack(LTNode* phead)
{
	assert(phead->next != phead);
	LTNode* tmp = phead->prev;
	phead->prev->prev->next = phead;//注意  倒数第二个变了仍可以通过phead找到它
	phead->prev = phead->prev->prev;
	free(tmp);
}
void LTPushFront(LTNode* phead, LTDataType x)
{
	LTNode* newnode = LTbuynode(x);
	newnode->prev = phead;
	newnode->next = phead->next;
	phead->next->prev = newnode;
	phead->next = newnode;

}
void LTPopFront(LTNode* phead)
{
	assert(phead->next != phead);
	LTNode* tmp = phead->next;
	phead->next->next->prev = phead;
	phead->next = phead->next->next;
	free(tmp);

}
//在pos位置之后插⼊数据/
void LTInsert(LTNode* pos, LTDataType x)
{
	LTNode* tmp = LTbuynode(x);
	tmp->prev = pos;
	tmp->next = pos->next;
	pos->next->prev = tmp;
	pos->next=tmp;
}
void LTErase(LTNode* pos)
{
	assert(pos->next != pos);
	pos->prev->next = pos->next;
	pos->next->prev = pos->prev;
	free(pos);
}
LTNode* LTFind(LTNode* phead, LTDataType x)
{
	LTNode* pcur = phead->next;
	while (pcur != phead)
	{
		if (pcur->val == x)
		{
			return pcur;
		}
		pcur = pcur->next;
	}
	return NULL;
}